import React, { useEffect, useState } from "react";
import { withRouter, RouteComponentProps } from "react-router-dom";
import "./index.scss";

export interface CatalogProps extends RouteComponentProps {}

export interface ComponentItem {
  title: string;
  key: string;
  type: "component";
}

type CatalogList = (FolderItem | ComponentItem)[];

export interface FolderItem {
  title: string;
  type: "folder";
  children: CatalogList;
}

const Catalog: React.FC<CatalogProps> = (props) => {
  const [catalog, setCatalog] = useState<CatalogList>([]);
  const [currentComponent, setCurrentComponent] = useState<string>();

  useEffect(() => {
    // fetch()
    fetch("docs/catalog.json")
      .then((res) => res.json())
      .then((res) => {
        setCatalog(res);
      });
  }, []);

  useEffect(() => {
    props.history.push(currentComponent ?? "/");
  }, [currentComponent]);

  function getFolder(list: CatalogList) {
    return (
      <ul>
        {list.map((item, idx) => {
          if (item.type === "component") {
            return getComponent(item, idx);
          } else {
            return (
              <li className={item.type} key={idx}>
                <span>{item.title}</span>
                {getFolder(item.children)}
              </li>
            );
          }
        })}
      </ul>
    );
  }

  function getComponent(component: ComponentItem, idx: number) {
    return (
      <li
        key={idx}
        className={`${component.type} ${
          component.key === currentComponent ? "active" : ""
        }`}
        onClick={() => setCurrentComponent(component.key)}
      >
        {component.title}
      </li>
    );
  }

  return (
    <aside className="catalog">
      {/* <ul>
        {catalog.map((item, idx) => (
          <li key={idx} className={`${item.type}`}>
            {item.title}
          </li>
        ))}
      </ul> */}
      {getFolder(catalog)}
    </aside>
  );
};

export default withRouter(Catalog);
